package server

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"os"
)

//图片服务器
func RunPicServer() {
	work_dir, err := os.Getwd()
	if err != nil {
		fmt.Println("work_dir err: ", err)
	}

	http.Handle("/", http.FileServer(http.Dir(work_dir+"/file")))
	err = http.ListenAndServe(":8088", nil)
	if err != nil {
		fmt.Println(err)
	}
}

//图片上传、下载
func RunPicUpload() {
	gin.DisableConsoleColor()

	// Logging to a file.
	f, _ := os.Create("gin.log")
	gin.DefaultWriter = io.MultiWriter(f, os.Stdout)

	r := gin.Default()
	r.POST("/file/upload", func(c *gin.Context) {
		//获取解析后表单
		form, _ := c.MultipartForm()
		//这里是多文件上传
		result := make(map[string]string)
		for key, files := range form.File {
			//fmt.Println("---", key)
			for _, file := range files {
				filename := file.Filename
				c.SaveUploadedFile(file, "./file/"+filename)
				result[key] = fmt.Sprintf("http://"+GlobalConf.ServerIP+":8088/%s", filename)
			}
		}
		//返回key对应的url
		c.JSON(200, SuccRet(result))
	})

	r.POST("/file/delete", func(c *gin.Context) {
		filename := c.PostForm("filename")
		os.Remove("./file/" + filename)
		c.JSON(200, SuccRet(nil))
	})

	r.Run(":8001")
}
